/**
 * 
 */
package neptune.manager.validator.rules.ipaddress;

import neptune.manager.model.topology.IPAddress;
import neptune.manager.utils.Logger.MessageType;
import neptune.manager.validator.ValidatorResult;
import neptune.manager.validator.ValidatorRule;
import neptune.manager.validator.Validator.Status;

/**
 * @author Roberto Bifulco [RobertoBifulco.it] [info@robertoBifulco.it]
 * 
 */
public class Ip4AddressFormatRule extends ValidatorRule<IPAddress> {

	@Override
	public String getName() {
		return "Ip4AddressFormatRule";
	}

	@Override
	protected ValidatorResult validationAlgorithm(IPAddress toValidate,
			ValidatorResult result) {

		if (toValidate.getAddress() != null
				&& !toValidate.getAddress().equals("")) {

			if (toValidate.getAddress().split("\\.").length == 4) {

				String[] numbers = toValidate.getAddress().split("\\.");
				for (String number : numbers) {
					try {
						int cypher = Integer.parseInt(number);

						if (cypher < 0 || cypher > 255) {
							result.setStatus(Status.ERROR);
							result.getLog().addMessage(
									"Address in bad format: "
											+ toValidate.getAddress(),
									MessageType.ERROR);
						}

					} catch (NumberFormatException e) {
						result.setStatus(Status.ERROR);
						result.getLog().addMessage(
								"Address in bad format: "
										+ toValidate.getAddress(),
								MessageType.ERROR);
					}
				}

			} else {
				result.setStatus(Status.ERROR);
				result.getLog().addMessage(
						"Address in bad format: " + toValidate.getAddress(),
						MessageType.ERROR);
			}

		} else {
			result.setStatus(Status.ERROR);
			result.getLog().addMessage("Address undefined", MessageType.ERROR);
		}

		return result;
	}

}
